package com.zuoyanit.unirtc;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;


import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;
import io.dcloud.feature.uniapp.ui.component.UniComponent;

import static com.tencent.trtc.TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL;
import static com.tencent.trtc.TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT;
import static com.tencent.trtc.TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL;
import static com.tencent.trtc.TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG;


public class RtcModule extends UniModule {
    private  String TAG ="testModel";
    private TRTCCloud mTRTCCloud;
    private Context context;
    private  JSONObject initOption;//包含sdkappid等



    /**
     *  trtc初始化
     * @param options
     * @param callback
     */
    @UniJSMethod(uiThread = false)
    public void init(JSONObject options, UniJSCallback callback) {
        this.initOption = options;
        this.context = this.mWXSDKInstance.getContext();
        this.mTRTCCloud = TRTCCloud.sharedInstance(context);
        this.mTRTCCloud.setListener(new TRTCCloudListener(){
            @Override
            public void onError(int i, String s, Bundle bundle) {
                super.onError(i, s, bundle);
                Log.e(TAG, "ERROR--"+s);
                if(callback != null) {
                    JSONObject data = new JSONObject();
                    data.put("code", 500);
                    data.put("type", "onError");
                    data.put("msg", s);
                    callback.invokeAndKeepAlive(data);
                }
            }

            @Override
            public void onEnterRoom(long result) {
                super.onEnterRoom(result);
                if(callback != null) {
                    JSONObject data = new JSONObject();
                    if (result > 0) {
                        data.put("code", 200);
                        data.put("type", "onEnterRoom");
                        data.put("data", "进房成功，总计耗时["+result+"])]ms");
                    } else {
                        data.put("code", 500);
                        data.put("type", "onEnterRoom");
                        data.put("data", "进房失败，错误码[("+result+")]");
                    }
                    callback.invokeAndKeepAlive(data);
                }
            }

            @Override
            public void onExitRoom(int i) {
                super.onExitRoom(i);
                if(callback != null) {
                    JSONObject data = new JSONObject();
                        data.put("code", 200);
                        data.put("type", "onExitRoom");
                        data.put("data",  i);
                }
            }

            //当房间中有其他用户在上行音频数据时，您会收到 onUserAudioAvailable() 事件通知
            // SDK 会自动播放远端用户的声音。
            @Override
            public void onUserVideoAvailable(String userId, boolean available) {
                Log.e("txvideo", "ERROR--onUserVideoAvailable"+userId+available+callback);
                if(available){//远程加入
                        JSONObject data = new JSONObject();
                            data.put("code", 200);
                            data.put("type", "onUserVideoAvailable");
                            data.put("data", userId);
                        callback.invokeAndKeepAlive(data);
                } else {//远程退出
                    JSONObject data = new JSONObject();
                    data.put("code", 200);
                    data.put("type", "onUserVideoAvailableExit");
                    data.put("data", userId);
                    callback.invokeAndKeepAlive(data);
                }
            }

            @Override
            public void onUserAudioAvailable(String userId, boolean available) {
                super.onUserAudioAvailable(userId, available);
                if(available){//远程加入
                    JSONObject data = new JSONObject();
                    data.put("code", 200);
                    data.put("type", "onUserAudioAvailable");
                    data.put("data", userId);
                    callback.invokeAndKeepAlive(data);
                } else {//远程退出
                    JSONObject data = new JSONObject();
                    data.put("code", 200);
                    data.put("type", "onUserAudioAvailableExit");
                    data.put("data", userId);
                    callback.invokeAndKeepAlive(data);
                }
            }
        });
    }

    /**
     * 进入房间
     */
    @UniJSMethod(uiThread = true)
    public void enterRoom(int roomId) {
        TRTCCloudDef.TRTCParams trtcParams = new TRTCCloudDef.TRTCParams();
        trtcParams.sdkAppId = this.initOption.getIntValue("sdkAppId");
        trtcParams.userId =this.initOption.getString("userId");
        trtcParams.roomId = roomId;
        trtcParams.userSig = this.initOption.getString("userSig");;
        //视频通话，请设置为TRTC_APP_SCENE_VIDEOCALL。
        //语音通话，请设置为TRTC_APP_SCENE_AUDIOCALL。
        mTRTCCloud.enterRoom(trtcParams, TRTC_APP_SCENE_VIDEOCALL);

    }

    /***
     * 开启远程视频
     * @param userId
     * @param viewid
     */
//    @UniJSMethod(uiThread = true)
//    public void startRemoteView(String userId, String viewid) {
////        mTRTCCloud.startRemoteView(userId, TRTC_VIDEO_STREAM_TYPE_BIG, tvv);
//    }


    /**
     * 开启预览
     */
//    @UniJSMethod(uiThread = true)
//    public void  startLocalPreview(String viewid) {//
////        int aa = this.context.getResources().getIdentifier(viewid,"id", this.context.getPackageName());
//        int aa = this.context.getApplicationContext().getResources().getIdentifier(viewid,null,null);
//        TXCloudVideoView tvv = (TXCloudVideoView) this.mWXSDKInstance.getRootView().findViewById(aa);
//        if(tvv != null) {
//            mTRTCCloud.startLocalPreview(true, tvv);
//        }
//        Log.e(TAG, "ERROR--startLocalPreview---aa"+aa);
//        Log.e(TAG, "ERROR--startLocalPreview---tvv"+tvv);
//        Log.e(TAG, "ERROR--startLocalPreview---"+viewid);
//    }

    /**
     * 开启预览
     */
    @UniJSMethod(uiThread = true)
    public void  startLocalPreview1(TXCloudVideoView tvv) {//
        Log.e(TAG, "ERROR--startLocalPreview---tvv"+tvv);
        if(tvv != null) {

            TRTCCloudDef.TRTCVideoEncParam p =  new TRTCCloudDef.TRTCVideoEncParam();
            mTRTCCloud.setLocalViewFillMode(TRTC_VIDEO_RENDER_MODE_FILL);
            mTRTCCloud.setVideoEncoderParam(p);
            mTRTCCloud.startLocalPreview(true, tvv);
            mTRTCCloud.startLocalAudio(TRTC_AUDIO_QUALITY_DEFAULT);
        }
    }

    /***
     * 退出房间
     */
    @UniJSMethod(uiThread = true)
    public void  exitRoom(){
        this.mTRTCCloud.exitRoom();
    }


    @UniJSMethod(uiThread = true)
    public void testAsyncFunc(JSONObject options, UniJSCallback callback) {
        Log.e(TAG, "testAsyncFunc--"+options);
        if(callback != null) {
            JSONObject data = new JSONObject();
            data.put("code", "success");
            callback.invoke(data);
        }
    }


    //run JS thread
    @UniJSMethod (uiThread = false)
    public JSONObject testSyncFunc(){
        JSONObject data = new JSONObject();
        data.put("code", "success");
        return data;
    }
}
